'use strict';

const RouterService = require('./base');

class CategoryService extends RouterService {
  constructor(ctx) {
    super(ctx, 'Category');
  }

  pageOrder() {
    return [['sort', 'ASC'], ['id', 'DESC']];
  }

  listOrder() {
    return [['sort', 'ASC'], ['id', 'DESC']];
  }

  async allList() {
    return super.allList({}, [
      {
        model: this.ctx.model.Product,
        as: 'children'
      }
    ]);
  }
  // 获取分类树形结构
  async getTree() {
    const allCategories = await this.allList();
    return this.buildTree(allCategories);
  }

  // 构建树形结构
  buildTree(categories, parentId = 0) {
    const result = [];
    categories.forEach(category => {
      if (category.parentId === parentId) {
        const children = this.buildTree(categories, category.id);
        if (children.length) {
          category.children = children;
        }
        result.push(category);
      }
    });
    return result;
  }
}

module.exports = CategoryService;
